#! /usr/bin/env python3
# vim:fenc=utf-8

# Copyright (c) 2025 Li Auto Inc. and its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from argparse import ArgumentParser
import json
import os

list_data = []
root_path = os.path.abspath(os.path.curdir)


def parse_args():
    parser = ArgumentParser()
    parser.add_argument('-d', '--dir', action='append', help='directory path')
    parser.add_argument('-t', '--target', default='./compile_commands.json', help='target file')

    return parser.parse_args()


def parser_file(file_path):
    with open(file_path, 'r') as file:
        contnet = file.readlines()

    oc_files, cmd = contnet[:2]
    o_file, c_file = oc_files.split(':')

    transform = {
        'command': cmd,
        'directory': root_path,
        'file': c_file.strip(),
        'output': o_file.strip(),
    }

    list_data.append(transform)


def main():
    args = parse_args()
    dir_lst = args.dir
    target = args.target

    if not target.endswith('json'):
        raise ValueError('Expecting input file to have a file extension of ".json".')

    for directory in dir_lst:
        if os.path.isdir(directory):
            for root, dirs, files in os.walk(directory):
                for file in files:
                    if file.endswith('.cmd'):
                        parser_file(os.path.join(root, file))
        else:
            print(f'{directory} is not a directory')

    with open(target, 'w') as f:
        json.dump(list_data, f, indent=4)

if __name__ == "__main__":
    main()
